﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;


namespace DotNetNuke.Modules.UserDefinedTable
{




  public class EditUrlDocument : EditControl
  {


    protected enum EditorViewEnum
    {
      ShowUpload,
      ShowLinkAndControls,
      ShowUrl
    }



    //private RadioButtonList _rblType;
    protected Label label;
    protected string lblRadioDoc;
    protected string lblRadioUrl;
    private UrlDocumentObject oDoc;
    protected string strDocumentFolder;

    //visual controls
    protected FileUpload upload;
    protected TextBox url;
    protected RadioButtonList radioBtnList;
    protected ImageButton cmdDeleteDocument;



    protected override void OnInit(EventArgs e)
    {

      base.OnInit(e);

      ///inner controls
      this.url = new TextBox();
      this.label = new Label();
      this.upload = new FileUpload();

      this.cmdDeleteDocument = new ImageButton();
      this.cmdDeleteDocument.EnableViewState = false;
      this.cmdDeleteDocument.ImageUrl = "~/images/delete.gif";
      this.cmdDeleteDocument.OnClientClick = "javascript:return confirm('" + DotNetNuke.Services.Localization.Localization.GetString("DeleteItem") + "');";
      this.cmdDeleteDocument.ToolTip = DotNetNuke.Services.Localization.Localization.GetString("cmdDelete.Text", this.ModuleContext.PortalSettings);
      this.cmdDeleteDocument.Click += new ImageClickEventHandler(cmdDeleteDocument_Click);

      this.strDocumentFolder = Convert.ToString(this.ModuleContext.Settings[SettingName.DocDataFolder]);

      if (string.IsNullOrEmpty(this.strDocumentFolder))
        throw new ModuleLoadException("Invalid def, Document data type must have DefaultFolder specified");

      this.lblRadioDoc = "doc";
      this.lblRadioUrl = "url";

      this.radioBtnList = new RadioButtonList();
      this.radioBtnList.EnableViewState = true;
      this.radioBtnList.AutoPostBack = true;
      this.radioBtnList.RepeatDirection = RepeatDirection.Horizontal;
      this.radioBtnList.SelectedIndexChanged += new EventHandler(radioBtnList_SelectedIndexChanged);

      this.radioBtnList.Items.Add(this.lblRadioUrl);
      this.radioBtnList.Items.Add(this.lblRadioDoc);

      this.url.EnableViewState = true;
      this.url.Width = Unit.Pixel(250);

      this.label.EnableViewState = true;
      this.upload.EnableViewState = false;

      this.Controls.Add(this.radioBtnList);
      this.Controls.Add(this.cmdDeleteDocument);
      this.Controls.Add(this.label);
      this.Controls.Add(this.upload);
      this.Controls.Add(this.url);

      _eventMgrCtl.onRowUpdate += new UDTdataEditor.onRowUpdateEventHandler(_eventMgrCtl_onRowUpdate); 
      _eventMgrCtl.onRowDelete += new UDTdataEditor.onRowDeleteEventHandler(_eventMgrCtl_onRowDelete);
      

      this.updateView(EditorViewEnum.ShowUrl);

      
    }




    protected void _deleteFile(string fileMoniker)
    {
      string strMsg = DocumentObject.DeleteDocument(ref fileMoniker);

      if ( !string.IsNullOrEmpty(strMsg) )
        throw new InvalidOperationException(strMsg);

      this.ViewState["value"] = "";
    }





    protected void _eventMgrCtl_onRowDelete()
    {
      //if there is a non empty value in viewstate there is file in portal that must be deleted
      if ( !string.IsNullOrEmpty((string)this.ViewState["value"]) )
      {
        oDoc = new UrlDocumentObject(this.ModuleId, (string)this.ViewState["value"]);

        if (oDoc.ContentType == UrlDocumentObject.UrlDocContentTypeEnum.Document)
          _deleteFile((string)this.ViewState["value"]);

      }
    }





    /// <summary>
    /// called by editor when row value is updated
    /// </summary>
    protected void _eventMgrCtl_onRowUpdate()
    {
      //if there was some file (view state is not empty) and user deleted this file (label = "")
      //delete old file
      if ( !string.IsNullOrEmpty((string)this.ViewState["value"])  && string.IsNullOrEmpty(label.Text) )
      {
        //create new UrlDocument, whatever type it is
        this.oDoc = new UrlDocumentObject(this.ModuleId, ((string)ViewState["value"]));

        if (oDoc.ContentType == UrlDocumentObject.UrlDocContentTypeEnum.Document)
        {
          this._deleteFile(Convert.ToString(this.ViewState["value"]));
          this.ViewState["value"] = "";
        }
      }

      if (this.upload.HasFile && (this.radioBtnList.SelectedItem.Value == this.lblRadioDoc))
      {
        this.oDoc = new UrlDocumentObject(this.ModuleId, ref this.upload, this.strDocumentFolder);
        this.ViewState["value"] = RuntimeHelpers.GetObjectValue(this.oDoc.ToMoniker());
      }

      else if ((this.radioBtnList.SelectedItem.Value == this.lblRadioUrl) && !string.IsNullOrEmpty(this.url.Text) )
        this.ViewState["value"] = this.url.Text;

      else if (((this.radioBtnList.SelectedItem.Value == this.lblRadioUrl) && string.IsNullOrEmpty(this.url.Text)) || ((this.radioBtnList.SelectedItem.Value == this.lblRadioDoc) & string.IsNullOrEmpty(this.url.Text)))
        this.ViewState["value"] = "";

    }






    protected void cmdDeleteDocument_Click(object sender, ImageClickEventArgs e)
    {
      this.label.Text = "";
      this.updateView(EditorViewEnum.ShowUpload);
    }





    protected override bool IsNull()
    {
      //isNull = no previous value, no new value or deleted previous without set new value
      return (radioBtnList.SelectedValue == lblRadioDoc && label.Text == "" && !upload.HasFile) ||
        (radioBtnList.SelectedValue == lblRadioUrl && url.Text == "");
    }





    protected override bool IsValidType()
    {

      //if value is empty then is always valid
      if ((radioBtnList.SelectedValue == lblRadioDoc && label.Text == "" && (!upload.HasFile)) 
          || (radioBtnList.SelectedValue == lblRadioUrl && url.Text == ""))
        return true;

      //if selected url, check url.text content
      if (radioBtnList.SelectedValue == lblRadioUrl)
        return UrlDocumentObject.IsUrlValid(url.Text);

      return true;
    }





    private void radioBtnList_SelectedIndexChanged(object sender, EventArgs e)
    {
      string val = this.radioBtnList.SelectedValue;

      if (val == this.lblRadioDoc)
        this.updateView(EditorViewEnum.ShowUpload);

      else if (val == this.lblRadioUrl)
        this.updateView(EditorViewEnum.ShowUrl);

    }





    protected void updateView(EditorViewEnum v)
    {
      switch (v)
      {
        case EditorViewEnum.ShowLinkAndControls:
          this.radioBtnList.SelectedIndex = this.radioBtnList.Items.IndexOf(this.radioBtnList.Items.FindByText(this.lblRadioDoc));
          this.radioBtnList.Style["display"] = "";
          this.cmdDeleteDocument.Style["display"] = "none";
          this.upload.Style["display"] = "";
          this.label.Style["display"] = "none";
          this.url.Style["display"] = "none";
          break;

        case EditorViewEnum.ShowUpload:
          this.radioBtnList.SelectedIndex = this.radioBtnList.Items.IndexOf(this.radioBtnList.Items.FindByText(this.lblRadioDoc));
          this.radioBtnList.Style["display"] = "none";
          this.cmdDeleteDocument.Style["display"] = "";
          this.upload.Style["display"] = "none";
          this.label.Style["display"] = "";
          this.url.Style["display"] = "none";
          break;

        case EditorViewEnum.ShowUrl:
          this.radioBtnList.SelectedIndex = this.radioBtnList.Items.IndexOf(this.radioBtnList.Items.FindByText(this.lblRadioUrl));
          this.radioBtnList.Style["display"] = "";
          this.cmdDeleteDocument.Style["display"] = "none";
          this.upload.Style["display"] = "none";
          this.label.Style["display"] = "none";
          this.url.Style["display"] = "";
          break;
      }
    }





    /// <summary>
    /// Gets/ sets A string consisting out of FileID|Original FileName
    /// get is used by data table to get data into
    /// set is used by data table to show/convert value to readable form ;-)
    /// </summary>
    public override string Value
    {
      get
      {
        return Convert.ToString(this.ViewState["value"]);
      }

      set
      {
        if (!string.IsNullOrEmpty(value))
        {
          //just create new document to ensure that is ok...
          this.oDoc = new UrlDocumentObject(this.ModuleId, value);
          //save value into viewstate
          this.ViewState["value"] = value;

          switch (this.oDoc.ContentType)
          { 
            case UrlDocumentObject.UrlDocContentTypeEnum.Document:
              if (!this.Page.IsPostBack)
                this.label.Text = Convert.ToString(this.oDoc.ToLink());

              this.updateView(EditorViewEnum.ShowLinkAndControls);
              break;

            case UrlDocumentObject.UrlDocContentTypeEnum.UrlLink:
              if (!this.Page.IsPostBack)
                this.url.Text = this.oDoc.ToUrl();

               this.updateView(EditorViewEnum.ShowUrl);
               break;
          }
        }
        else
          //default view is showUrl
          this.updateView(EditorViewEnum.ShowUrl);

      }
    }



  }

}

